import 'package:dk_flutter_base/dk_core.dart';
import 'package:dk_flutter_base/dk_ui.dart';
import 'package:dk_flutter_module_sale/common/config/page_base_common.dart';
import 'package:dk_flutter_module_sale/r.dart';
import 'package:dk_flutter_module_sale/sale/api/sale_in_api.dart';
import 'package:dk_flutter_module_sale/sale/sale_in/contract_pay_failure/bean/bean_contract_payment_item.dart';

class PayResultListWidget extends StatefulWidget {
  final ContractPayResultListBean initListBean;
  final CommonPageBloc pageBloc;
  final int pageSource; //0付款失败，1失败处理历史
  PayResultListWidget(this.initListBean, this.pageBloc, {this.pageSource});
  @override
  _PayResultListWidgetState createState() => _PayResultListWidgetState();
}

class _PayResultListWidgetState extends State<PayResultListWidget> {
  List<String> listItemTitles;
  List<String> listItemValues;
  DkEasyRefreshController easyRefreshController;
  Map<String, dynamic> paramsMap;
  int pageIndex = 1;
  ContractPayResultListBean listBean;
  @override
  void initState() {
    super.initState();
    listBean = widget.initListBean;
    easyRefreshController = DkEasyRefreshController();
    paramsMap = new Map<String, dynamic>();
    paramsMap['page'] = 1;
    paramsMap['page_num'] = 20;
    if (widget.pageSource == 0) {
      paramsMap['execute_status'] = '进行中';
    } else {
      paramsMap['execute_status'] = '已完成';
    }
    listItemTitles = _getItemTitles();
  }

  @override
  Widget build(BuildContext context) {
    bool noMore = pageIndex >= listBean.lastPage;
    return Container(
      height: double.infinity,
      width: 375,
      color: DkColor('0xfff5f5f5'),
      child: DkRefreshListWidget.custom(
          controller: easyRefreshController,
          onRefresh: refreshList,
          onLoad: noMore ? null : loadMore,
          emptyWidget: listEmpty(listBean.payList) ? _buildEmptyPage() : null,
          slivers: <Widget>[
            SliverList(
              delegate: SliverChildBuilderDelegate(
                (BuildContext context, int index) {
                  ContractPaymentListItemBean itemBean =
                      listBean.payList[index];
                  listItemValues = _getItemValues(itemBean);
                  return Column(
                    children: <Widget>[
                      Container(
                        height: 10,
                        color: DkColor('0xfff5f5f5'),
                      ),
                      Column(
                          children: listItemTitles.asMap().keys.map((index) {
                        return Container(
                            color: Colors.white,
                            padding: EdgeInsets.only(top: 14),
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                Container(
                                  width: 125,
                                  padding: EdgeInsets.only(left: 16, right: 5),
                                  child: DkText.simple(
                                    listItemTitles[index],
                                    14,
                                    DkColor('0Xff999999'),
                                    fontWeight: FontWeight.normal,
                                  ),
                                ),
                                Flexible(
                                  child: Padding(
                                    padding: EdgeInsets.only(right: 8),
                                    child: DkText.simple(listItemValues[index],
                                        14, DkColor('0Xff333333'),
                                        fontWeight: FontWeight.normal),
                                  ),
                                )
                              ],
                            ));
                      }).toList()),

                      Container(
                        height: 19,
                        color: Colors.white,
                      ),
                      DkVisibilityCompose(VisibilityComposeOption.gone(
                          (BuildContext itemContext) {
                        return Column(
                          children: <Widget>[
                            DkDivider(DividerOption.horizontal(height: 1)),
                            Container(
                              color: Colors.white,
                              padding: EdgeInsets.symmetric(
                                  vertical: 10, horizontal: 16),
                              alignment: Alignment.centerLeft,
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.start,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: <Widget>[
                                  Wrap(
                                    spacing: 10,
                                    runSpacing: 10,
                                    children: <Widget>[
                                      _buildBorderButton('查看付款计划',
                                          itemBean.contractPaymentUrl),
                                      itemBean.canChangebankNew
                                          ? _buildBorderButton('变更账户信息',
                                              itemBean.changebankNewUrl)
                                          : SizedBox(),
                                      itemBean.canChangebankShow
                                          ? _buildBorderButton('查看变更详情',
                                              itemBean.changebankShowUrl)
                                          : SizedBox(),
                                    ],
                                  )
                                ],
                              ),
                            )
                          ],
                        );
                      },
                          visible: ((itemBean.canChangebankNew ||
                                  itemBean.canChangebankShow) &&
                              !listBean.isLeader))), //不是leader才可能展示按钮
                    ],
                  );
                },
                childCount: listBean.payList.length,
              ),
            ),
          ]),
    );
  }

  List<String> _getItemTitles() {
    var titleList = ['合同编号', '房源地址', '业主信息', '付款失败原因', '付款失败时间'];
    if (widget.pageSource == 0) {
      titleList.add('当前状态');
    } else {
      titleList.add('付款成功时间');
    }
    if (listBean.isLeader) {
      titleList.add('责任销售');
    }
    return titleList;
  }

  List<String> _getItemValues(ContractPaymentListItemBean item) {
    String landLordInfo = item.landlordName + '  ' + item.landlordPhone ?? '';
    var valueList = [
      item.contractNumber ?? '',
      item.suiteId + '  ' + item.suiteAddress ?? '',
      landLordInfo,
      item.payFailedReason ?? '',
      item.payFailedDate ?? '',
    ];
    if (widget.pageSource == 0) {
      valueList.add(item.status ?? '');
    } else {
      valueList.add(item.paySucessfulDate ?? '');
    }
    if (listBean.isLeader) {
      //如果是leader
      valueList.add(item.executorName ?? '');
    }
    return valueList;
  }

  //底部带边框按钮
  Widget _buildBorderButton(title, url) {
    return GestureDetector(
      child: Container(
        padding: EdgeInsets.symmetric(vertical: 2, horizontal: 5),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(2.0)),
          border: Border.all(width: 1, color: DkColor('0xFF50D0D9')),
        ),
        child: DkText.simple(
          title,
          16,
          DkColor('0xFF50D0D9'),
          fontWeight: FontWeight.normal,
        ),
      ),
      onTap: () {
        if (stringNotEmpty(url)) {
          RouteUtil.goPage(url);
        }
      },
    );
  }

  //空页面
  Widget _buildEmptyPage() {
    if (widget.pageSource == 0) {
      //付款失败空页面
      return Container(
        color: Colors.white,
        child: Column(
          children: <Widget>[
            Container(
              alignment: Alignment.topLeft,
              height: 44,
              color: Colors.white,
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  Padding(
                    padding: EdgeInsets.only(top: 10, left: 15),
                    child: Image.asset(
                      R.imagesSaleinTipIconPng,
                      width: 13,
                      height: 13,
                      fit: BoxFit.fill,
                    ),
                  ),
                  Center(
                      child: Padding(
                    padding: EdgeInsets.only(left: 6),
                    child: DkText.simple(
                      '后续如有业主首付款/续付款失败的合同会展示在这里，请根据失败\n原因变更账户信息',
                      11,
                      DkColor('0xffFAA0A0'),
                      fontWeight: FontWeight.normal,
                    ),
                  )),
                ],
              ),
            ),
            DkDivider(DividerOption.horizontal(
                height: 1, color: DkColor('0xffEBEBEB'))),
            _buildEmptyContent('当前暂无付款失败\n需处理的合同', EdgeInsets.only(top: 60))
          ],
        ),
      );
    } else {
      return _buildEmptyContent('当前暂无付款失败\n处理历史', EdgeInsets.only(top: 104));
    }
  }

  Widget _buildEmptyContent(text, padding) {
    return Container(
        padding: padding,
        color: Colors.white,
        child: Column(
          children: <Widget>[
            Image.asset(
              R.imagesSaleinPayFailureEmptyPng,
              width: 136,
              height: 136,
              fit: BoxFit.fill,
            ),
            SizedBox(
              height: 16,
            ),
            Center(
                child: Text(
              text,
              textAlign: TextAlign.center,
              style: TextStyle(
                  color: DkColor('0xff999999'), fontSize: 14, height: 1.4),
            ))
          ],
        ));
  }

  //-------------------refresh loadmore
  Future<void> refreshList({showLoading = false}) {
    pageIndex = 1;
    paramsMap['page'] = pageIndex;
    widget.pageBloc.dataHttpGet(
        path: SaleInApi.paymentFailureUrl,
        queryMap: paramsMap,
        handleResult: (dynamic data) {
          setState(() {
            listBean = ContractPayResultListBean.fromJson(data);
            easyRefreshController.finishRefresh(success: true);
          });
        },
        showLoading: showLoading,
        handleErrorCode: (responseData) {
          setState(() {
            showShortToast(responseData.msg);
            easyRefreshController.finishRefresh(success: false);
          });
        },
        handleFailResult: (dynamic data1, dynamic data2) {
          setState(() {
            easyRefreshController.finishRefresh(success: false);
          });
        });
    return new Future.value();
  }

  Future<void> loadMore() async {
    paramsMap['pageIndex'] = (++this.pageIndex);
    widget.pageBloc.dataHttpGet(
        path: SaleInApi.paymentFailureUrl,
        queryMap: paramsMap,
        handleResult: (dynamic data) {
          setState(() {
            ContractPayResultListBean moreBean =
                ContractPayResultListBean.fromJson(data);
            listBean.payList.addAll(moreBean.payList);
            easyRefreshController.finishLoad(
                success: true, noMore: this.pageIndex >= moreBean.lastPage);
          });
        },
        showLoading: false,
        handleFailResult: (dynamic data1, dynamic data2) {
          easyRefreshController.finishLoad(success: false);
        },
        handleErrorCode: (dynamic data1) {
          easyRefreshController.finishLoad(success: false);
        });
  }
}
